import axios from "axios";
import store from "../store";
import router from "../router";
import { Message } from "element-ui";
import { SET_TOKEN } from "../store/mutation-type";
axios.defaults.baseURL = "http://localhost:8888/api/private/v1/";
axios.defaults.timeout = 10000;
function http(url, method = "GET", params = {}, data = {}) {
  return axios({
    url,
    method,
    data,
    params,
    headers: {
      Authorization: store.state.token,
    },
  })
    .then((res) => {
      if (res.status >= 200 && res.status < 300) {
        //http状态码
        if (res.data.meta.status == 200) {
          //后台接口定义的状态码
          return res.data;
        } else {
          if (res.data.meta.msg === "无效token") {
            router.replace({
              name: "Login",
            });
          }
          store.commit(SET_TOKEN, "");
          return Promise.reject(res.data.meta.msg);
        }
      } else {
        return Promise.reject(res.statusText);
      }
    })
    .catch((err) => {
      Message({
        message: err,
        type: "error",
      });
    });
}

export default http;
